package com.hzt.utils;


import com.hzt.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述:
 * @author: huangzhitao
 * @date: 2021/3/21 2:35 上午
 */
@Component
public class HtmlParseUtils {
    public static void main(String[] args) throws Exception {
        new HtmlParseUtils().parseJD("对象").forEach(System.out::println);

    }

    public List<Content> parseJD(String keyword) throws Exception {
        String url = "https://search.jd.com/Search?keyword="+keyword;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> list = new ArrayList<>();
        for (Element el : elements) {
            //图片有个懒加载的过程
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
            list.add(content);
        }
            return list;
    }
}